<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="showRoleDialog('add')">添加角色</el-button>
      <el-table :data="tableData" border style="width: 100%">
        <template v-slot="scopeInfo">
          <el-table-column type="expand">
            <template v-slot="scopeInfo">
              <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
                      v-for="(item1, i1) in scopeInfo.row.children"
                      :key="item1.id">
                <!--渲染一级权限-->
                <el-col :span="5">
                  <el-tag closable @close="removeRole(scopeInfo.row, item1.id)">{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!--渲染二三级权限-->
                <el-col :span="19">
                  <!--渲染二级权限-->
                  <el-row
                    :class="['bdbottom', i2===0?'bdtop':'', 'vcenter']"
                    v-for="(item2, i2) in item1.children"
                    :key="item2.id">
                    <el-col :span="6">
                      <el-tag type="success" closable @close="removeRole(scopeInfo.row, item2.id)">{{item2.authName}}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag type="warning"
                              @close="removeRole(scopeInfo.row, item3.id)"
                              closable v-for="(item3) in item2.children"
                              :key="item3.id">
                        {{item3.authName}}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="roleName" label="角色名称"></el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
          <el-table-column prop="date" label="操作" width="300px">
            <template v-slot="scope">
              <el-button size="mini" type="primary" icon="el-icon-edit" @click="showRoleDialog('edit',scope.row.id)">
                编辑
              </el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRole(scope.row.id)">删除
              </el-button>
              <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">
                分配权限
              </el-button>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </el-card>

    <!-- 编辑权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="editPowerDialogVisible"
      width="80%"
      @closed="handleClose">
      <el-tree
        :data="rightslist"
        :show-checkbox="true"
        node-key="id"
        :default-expand-all="true"
        :props="treeProps"
        :default-checked-keys="defKeys"
        ref="treeRef">
      </el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editPowerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights()">确 定</el-button>
  </span>
    </el-dialog>

    <!--  添加、编辑角色  -->
    <el-dialog
      title="提示"
      :visible.sync="addDialogVisible"
      width="50%"
      @closed="handleClose">
      <el-form :model="addRoleInfo" :rules="addRoleRules" ref="addRoleRef" label-width="130px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleInfo.roleName" placeholder="请输入角色名称" maxlength="20" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleInfo.roleDesc" type="textarea" :rows="6" resize="none" maxlength="100"
                    show-word-limit
                    placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addRole">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  apiGetRoles,
  apiDeleteRolePower,
  apiQueryRights,
  apiSetRoles,
  apiSetRole,
  apiDeleteRole,
  apiEditRole,
  apiGetRole
} from '@/api/index.js'

export default {
  name: 'roles',
  created () {
    this.getRoles()
  },
  data () {
    return {
      tableData: [],
      editPowerDialogVisible: false,
      rightslist: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defKeys: [],
      roleId: '',
      //  添加角色
      addDialogVisible: false,
      addRoleInfo: {
        roleName: '',
        roleDesc: ''
      },
      addRoleRules: {
        'roleName': [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      // 添加、编辑角色 对话框区分
      roleDialog: {
        type: '',
        id: ''
      }
    }
  },
  methods: {
    // 获取权限信息
    async getRoles () {
      let { data: res } = await apiGetRoles()
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.status, res.meta.msg)
      }
      this.tableData = res.data
    },
    // 删除权限
    async removeRole (role, rightId) {
      let isSure = await this.$confirm('此操作将删除该角色权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message.info('已取消删除')
      })

      // 取消删除后 返回
      if (isSure !== 'confirm') {
        return
      }

      let { data: res } = await apiDeleteRolePower({
        roleId: role.id,
        rightId: rightId
      })

      if (res.meta.status !== 200) {
        return this.$message(res.meta.status, res.meta.msg)
      }

      role.children = res.data
      this.$message.success('删除成功')
    },
    // 打开编辑权限对话框
    async showSetRightDialog (info) {
      this.editPowerDialogVisible = true
      const { data: res } = await apiQueryRights('tree')
      if (res.meta.status !== 200) {
        return this.$message(res.meta.status, res.meta.msg)
      }
      this.rightslist = res.data
      this.getLeafKeys(info, this.defKeys)
      this.roleId = info.id
    },
    // 遍历选中的key
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 对话框关闭 重置数据
    handleClose () {
      this.defKeys = []
      this.addRoleInfo.roleName = ''
      this.addRoleInfo.roleDesc = ''
      this.typeDialog = ''
      this.$refs.addRoleRef.resetFields()
    },
    // 编辑权限
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await apiSetRoles(this.roleId, idStr)
      this.editPowerDialogVisible = false
      if (res.meta.status !== 200) {
        return this.$message(res.meta.status, res.meta.msg)
      }
      this.$message.success('操作成功')
      this.getRoles()
    },
    // 弹出添加、编辑角色对话框
    async showRoleDialog (type, id = '') {
      this.addDialogVisible = true
      this.roleDialog.type = type
      if (type === 'edit') {
        this.roleDialog.id = id
        const { data: res } = await apiGetRole(this.roleDialog.id)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.status, res.meta.msg)
        }
        this.addRoleInfo.roleName = res.data.roleName
        this.addRoleInfo.roleDesc = res.data.roleDesc
      }
      console.log(this.roleDialog)
    },
    // 添加角色
    async addRole () {
      if (this.roleDialog.type === 'add') {
        // 添加角色接口
        const { data: res } = await apiSetRole(this.addRoleInfo)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.status, res.meta.msg)
        }
      } else {
        // TODO 编辑角色接口
        const { data: res } = await apiEditRole(this.roleDialog.id, this.addRoleInfo)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.status, res.meta.msg)
        }
      }
      this.addDialogVisible = false
      this.getRoles()
      this.$message.success('操作成功')
    },
    // 删除角色
    async deleteRole (id) {
      let result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
      })
      if (result !== 'confirm') return false
      const { data: res } = await apiDeleteRole(id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.status, res.meta.msg)
      }
      this.getRoles()
      this.$message.success('操作成功')
    }
  }
}
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }

  .bdtop {
    border-top: 1px solid #eee;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }
</style>
